<?php

/*
 * Copyright (c) 2009, Nguyen Duc Thuan <me@ndthuan.com>
 * All rights reserved.
 */

class Fete_Logger
{
    protected $_dir = null;
    protected $_file = null;

    public function __construct($dir = null)
    {
        if (null !== $dir) {
            $this->_dir = $dir;
        }
    }

    /**
     *
     * @param string $dir
     * @return Fete_Logger
     */
    static public function createInstance($dir = null)
    {
        return new self($dir);
    }

    /**
     *
     * @param string $message
     * @param integer $timestamp
     * @return Fete_Logger
     */
    public function &log($message, $timestamp = null, $file = null) 
    {
        if (null === $this->_dir) {
            throw new Fete_Log_Exception('Log directory is not set');
            return $this;
        }

        if (null === $timestamp) {
            $timestamp = time();
        }
        
        if (null !== $file) {
            if (!file_exists($file)) {
                $file = $this->_dir . DIRECTORY_SEPARATOR . $file;
            }
        } elseif (null !== $this->_file) {
            if (!file_exists($this->_file)) {
                $file = $this->_dir . DIRECTORY_SEPARATOR . $this->_file;
            } else {
                $file = $this->_file;
            }
        } else {
            $file = $this->_dir . DIRECTORY_SEPARATOR
                . date('Y-m-d', $timestamp) . '.log';
        }

        $fh = fopen($file, 'a');
        fwrite($fh, date('Y-m-d H:i:s', $timestamp) . ' :: ' . $message
            . "\n===========\n");
        fclose($fh);

        return $this;
    }

    /**
     *
     * @param string $dir
     * @return Fete_Logger
     */
    public function &setDir($dir) 
    {
        $this->_dir = $dir;

        return $this;
    }

    public function &setFile($file)
    {
        $this->_file = $file;

        return $this;
    }
}